<?php

/**
 * User:ayou chow
 * Date: 2020-02-07
 * Time: 15:19
 */

namespace app\admin\controller;


use app\common\model\BasketAreaModel;
use app\common\model\BasketCountryModel;
use app\common\model\BasketMatchAnchorModel;
use app\common\model\BasketMatcheventModel;
use app\common\model\BasketMatchModel;
use app\common\model\BasketMatchRecModel;
use app\common\model\BasketTeamModel;
use app\common\model\UserModel;
use think\facade\Request;

class BasketballController extends BaseController {
    protected function initialize() {
        parent::initialize();
        $action_name = Request::instance()->action();
        $this->assign('action_name', $action_name);
    }

    public function area() {
        $area = BasketAreaModel::select();
        $this->assign('area', $area);
        return $this->fetch();
    }

    public function country() {
        $country = BasketCountryModel::with(['area'])->select();
        $this->assign('country', $country);
        return $this->fetch();
    }

    public function matchevent() {
        return $this->fetch();
    }

    public function match() {
        return $this->fetch();
    }

    public function team() {
        return $this->fetch();
    }

    public function recmatch() {
        return $this->fetch();
    }

    public function matchanchor() {
        $match = BasketMatchModel::where(['id' => Request::param('id')])->with(['matchevent', 'hometeam', 'awayteam'])->find();
        $this->assign('match', $match);
        return $this->fetch();
    }

    public function matcheventlist() {
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $list = BasketMatcheventModel::with(['area', 'country'])->limit(($page - 1) * $limit, $limit)->select();
        if (count($list) > 0) {
            $count = BasketMatcheventModel::count("id");
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function teamlist() {
        $page  = Request::param("page");
        $limit = Request::param("limit");
        $list  = BasketTeamModel::with(['matchevent'])->limit(($page - 1) * $limit, $limit)->select();
        if (count($list) > 0) {
            $count = BasketTeamModel::count("id");
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function matchlist() {
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $sporttype     = Request::param('sporttype');
        $matchid       = Request::param('matchid');
        $competitionid = Request::param('competitionid');
        $hometeamid    = Request::param('hometeamid');
        $awayteamid    = Request::param('awayteamid');
        $status        = Request::param('status');
        $start_time    = Request::param('start_time');
        $end_time      = Request::param('end_time');

        $where          = [];
        $whereTimeStart = '';
        $whereTimeEnd   = '';

        if ($matchid) {
            $where['id'] = $matchid;
        }

        if ($competitionid) {
            $where['competition_id'] = $competitionid;
        }

        if ($hometeamid) {
            $where['home_id'] = $hometeamid;
        }

        if ($awayteamid) {
            $where['away_id'] = $awayteamid;
        }

        if (($status || $status === '0') && $status != '999') {
            $where['status'] = $status;
        }

        if ($start_time) {
            $timstrap       = strtotime($start_time);
            $whereTimeStart = "time >= {$timstrap}";
        }

        if ($end_time) {
            $timstrap     = strtotime($end_time);
            $whereTimeEnd = "time <= {$timstrap}";
        }

        /*
        if ($sporttype && $sporttype != 0){
            switch($sporttype){
                case 1:
                    break;
                case 2:
                    break;
            }
        } else{
            $Basket = BasketMatchModel::where($where)->where($whereTimeStart)->where($whereTimeEnd)->with(['matchevent','hometeam','awayteam','rec','live'])->order(['time'=>'desc'])->limit(($page-1)*$limit,$limit)->select();
        
        }
*/
        $list = BasketMatchModel::where($where)->where($whereTimeStart)->where($whereTimeEnd)->with(['matchevent', 'hometeam', 'awayteam', 'rec', 'url', 'live'])->order(['time' => 'desc'])->limit(($page - 1) * $limit, $limit)->select();
        if (count($list) > 0) {
            $count = BasketMatchModel::where($where)->where($whereTimeStart)->where($whereTimeEnd)->count("id");
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function recmatchlist() {
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $competitioninfo = Request::param('competitioninfo');
        $teaminfo        = Request::param('teaminfo');
        $status          = Request::param('status');
        $start_time      = Request::param('start_time');
        $end_time        = Request::param('end_time');

        $where                = [];
        $whereTimeStart       = '';
        $whereTimeEnd         = '';
        $whereteam            = '';
        $wherecompetitioninfo = '';

        if ($competitioninfo) {
            $wherecompetitioninfo = "matchevent.id like '%{$competitioninfo}%' 
            or match.id like '%{$competitioninfo}%'
            or matchevent.name_zh like '%{$competitioninfo}%'";
        }

        if ($teaminfo) {
            $whereteam = "home_id like '%{$teaminfo}%' 
            or away_id like '%{$teaminfo}%' 
            or hometeam.name_zh like '%{$teaminfo}%' 
            or awayteam.name_zh like '%{$teaminfo}%'";
        }

        if (($status || $status === '0') && $status != '999') {
            $where['status'] = $status;
        }

        if ($start_time) {
            $timstrap       = strtotime($start_time);
            $whereTimeStart = "time >= {$timstrap}";
        }

        if ($end_time) {
            $timstrap     = strtotime($end_time);
            $whereTimeEnd = "time <= {$timstrap}";
        }

        $matchs = BasketMatchRecModel::alias('res')
            ->join('db_basket_match match', 'res.matchid = match.id')
            ->join('db_basket_team hometeam', 'match.home_id = hometeam.id')
            ->join('db_basket_team awayteam', 'match.away_id = awayteam.id')
            ->join('db_basket_matchevent matchevent', 'match.competition_id = matchevent.id')
            ->field('match.id as match_id, matchevent.id as matchevent_id, matchevent.name_zh as matchevent_name_zh,
            match.home_id, match.away_id, hometeam.name_zh as hometeam_name_zh, awayteam.name_zh as awayteam_name_zh,
            match.status, match.time, match.away_score, match.away_overtime,
            match.home_score, match.home_overtime, match.kickoff_time, res.id')
            ->where($whereteam)->where($wherecompetitioninfo)->where($where)->where($whereTimeStart)->where($whereTimeEnd)
            ->order(['time' => 'desc'])->limit(($page - 1) * $limit, $limit)->select();

        if (count($matchs) > 0) {
            $count = BasketMatchRecModel::alias('res')
                ->join('db_basket_match match', 'res.matchid = match.id')
                ->join('db_basket_team hometeam', 'match.home_id = hometeam.id')
                ->join('db_basket_team awayteam', 'match.away_id = awayteam.id')
                ->join('db_basket_matchevent matchevent', 'match.competition_id = matchevent.id')
                ->where($whereteam)->where($wherecompetitioninfo)->where($where)->where($whereTimeStart)->where($whereTimeEnd)
                ->count();
            return json(["code" => 0, "msg" => "", "data" => $matchs, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function recmatch_post() {
        $id             = Request::param('id');
        $data_source_id = Request::param('data_source_id');
        $third_id       = Request::param('third_id');
        //查询是否已推荐
        $rec = BasketMatchRecModel::where(['matchid' => $id])->find();
        if ($rec) {
            return self::bulidSuccess();
        }
        $rec = new BasketMatchRecModel(['matchid' => $id, 'data_source_id' => $data_source_id, 'third_id' => $third_id, 'create_time' => nowFormat()]);
        if ($rec->save()) {
            // 记录日志
            $log_content = "设置推荐篮球赛事，比赛ID：{$rec->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function unsetrecmatch_post() {
        $id = Request::param('id');
        //查询是否已推荐
        $rec = BasketMatchRecModel::where(['matchid' => $id])->find();
        if (!$rec) {
            return self::bulidSuccess();
        }
        if ($rec->delete()) {
            // 记录日志
            $log_content = "取消推荐篮球赛事，比赛ID：{$rec->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function delrecmatch_post() {
        $id = Request::param('id');
        //查询是否已推荐
        $rec = BasketMatchRecModel::where(['id' => $id])->find();
        if (!$rec) {
            return self::bulidSuccess();
        }
        if ($rec->delete()) {
            // 记录日志
            $log_content = "取消推荐篮球赛事，比赛ID：{$rec->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function getmatchanchorlist() {
        $matchid      = Request::param('matchid');
        $page         = Request::param("page");
        $limit        = Request::param("limit");
        $matchanchors = BasketMatchAnchorModel::with('anchor')->where(['matchid' => $matchid])->limit(($page - 1) * $limit, $limit)->select();
        if (count($matchanchors) > 0) {
            $count   = BasketMatchRecModel::where(['matchid' => $matchid])->count("id");
            $anchors = [];
            foreach ($matchanchors as $matchanchor) {
                $anchors[] = $matchanchor->anchor;
            }
            return json(["code" => 0, "msg" => "", "data" => $anchors, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function addmatchanchor_post() {
        $ids      = Request::param('ids');
        $matchid  = Request::param('matchid');
        $id_array = explode(',', $ids);
        $anchors  = UserModel::where('id', 'in', $id_array)->where(['is_anchor' => 1])->field('id,nick_name')->select();
        $data     = [];
        foreach ($anchors as $anchor) {
            $data[] = ['matchid' => $matchid, 'anchorid' => $anchor->id, 'create_time' => nowFormat()];
        }
        $matchanchor = new BasketMatchAnchorModel();
        if ($matchanchor->saveAll($data)) {
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function delmatchanchor_post() {
        $anchorid    = Request::param('anchorid');
        $matchid     = Request::param('matchid');
        $matchanchor = BasketMatchAnchorModel::where(['anchorid' => $anchorid, 'matchid' => $matchid])->find();
        if (!$matchanchor) {
            return self::bulidSuccess();
        }
        if ($matchanchor->delete()) {
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }
}
